
imgfiles = dir('OneCell.re-aligned.0198/OneCell*.tif');

filesize = numel(imgfiles);

midsize = uint8(round(filesize/2));

fiximg = imread(imgfiles(midsize).name);
fiximg = imresize(fiximg, 0.25);
%fiximg = imcrop(fiximg,[1 1 288 288]);
outputFileName  = strcat('register_output2/OneCelloutput',sprintf('%04d',midsize),'.png');
imwrite(fiximg, outputFileName);
%figure, imshow(fiximg);
% Imoving=imread('images/lenag1.png');
% Istatic=imread('images/lenag3.png');

%% previous displacement field
pBx = zeros(size(fiximg,1),size(fiximg,2));
pBy = zeros(size(fiximg,1),size(fiximg,2));

options = struct('Similarity','p','Registration','NonRigid','SigmaFluid',4,...
    'Alpha',4,'SigmaDiff',1,'Interpolation','Linear','maxiter',500);

affineMat = zeros(3, 3, midsize-1);

% for i = midsize-1:-1:1
%     movingimg = imread(imgfiles(i).name);
%     movingimg = imresize(movingimg, 0.25);
%     %movingimg = imcrop(movingimg,[1 1 288 288]);
%     %figure, imshow(movingimg);
%     %[Ireg,Bx,By,Fx,Fy] = affineregister_images(Imoving,Istatic,1,1,options);
%     [Ireg,Bx,By,Fx,Fy] = register_images(movingimg,fiximg,options);
%     Ireg = movepixels(Ireg,pBx,pBy,[], 3);
%     outputFileName  = strcat('register_output2/OneCelloutput',sprintf('%04d',i),'.png');
%     imwrite(Ireg,outputFileName);
%     
%     %% update fiximg and previous displacement field
%     [pBx,pBy] = VFcomposition(pBx, pBy, Bx, By, size(Bx,2), size(Bx,1));
%     fiximg = movingimg;
%     close all
%     %figure, imshow(Ireg);
% end

for i = midsize+1:1:filesize
    movingimg = imread(imgfiles(i).name);
    movingimg = imresize(movingimg, 0.25);
    %movingimg = imcrop(movingimg,[1 1 288 288]);
    %figure, imshow(movingimg);
    %[Ireg,Bx,By,Fx,Fy] = affineregister_images(Imoving,Istatic,1,1,options);
    [Ireg,Bx,By,Fx,Fy] = register_images(movingimg,fiximg,options);
    Ireg = movepixels(Ireg,pBx,pBy,[], 3);
    outputFileName  = strcat('register_output2/OneCelloutput',sprintf('%04d',i),'.png');
    imwrite(Ireg,outputFileName);
    
    %% update fiximg and previous displacement field
    [pBx,pBy] = VFcomposition(pBx, pBy, Bx, By, size(Bx,2), size(Bx,1));
    fiximg = movingimg;
    %close all
    %figure, imshow(Ireg);
end
